package test.http;

import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import test.IO.Output;
import test.config.Config;

public class HTTPClient {
	// http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
	public static HTTPResponse excutePost(HttpURLConnection connection,
			String targetURL, String urlParameters, String cookie) {
		try {
			// Create connection
			// connection = (HttpURLConnection) url.openConnection();
			connection = Connector.openConnection(targetURL, Config.isProxy());
			connection.setRequestMethod("POST");
			if (urlParameters != null) {

				connection.setRequestProperty("Content-Length", ""
						+ Integer.toString(urlParameters.getBytes().length));
			}
			connection.setRequestProperty("Content-Language", "en-US");
			connection.setRequestProperty("Cookie", cookie);

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request
			DataOutputStream wr = new DataOutputStream(connection
					.getOutputStream());
			if (urlParameters != null) {
				wr.writeBytes(urlParameters);
			}
			wr.flush();
			wr.close();

			// Get Response
			InputStream is = connection.getInputStream();

			Map<String, List<String>> headers = connection.getHeaderFields();
			List<String> values = headers.get("Set-Cookie");

			String cookieValue = null;

			if (values != null) {
				for (String value : values) {
					if (cookieValue == null) {
						cookieValue = value;
					} else {
						cookieValue = cookieValue + ";" + value;
					}
				}
			} else {
				cookieValue=cookie;
			}
			
			Output.log("Cookie: "+cookieValue);

			String stramString = Output.inputStreamToString(is);
			ByteArrayInputStream responseStream = new ByteArrayInputStream(
					stramString.getBytes());

			return new HTTPResponse(responseStream, cookieValue);

		} catch (Exception e) {

			e.printStackTrace();
			return null;

		} finally {

			if (connection != null) {
				connection.disconnect();
			}
		}
	}
}
